package com.jiantong.admin.controller;

import com.google.common.base.CharMatcher;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.user.enums.LoginType;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.OrganizationUser;

import com.jiantong.user.model.User;
import com.jiantong.user.model.UserProfile;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.user.service.OrganizationUserReadService;
import com.jiantong.user.service.UserProfileReadService;
import com.jiantong.user.service.UserReadService;

import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cao on 2017/7/15.
 */
@Controller
public class ManagerController {
    @RpcConsumer
    private OrganizationUserReadService organizationUserReadService;
    @RpcConsumer
    private UserReadService<User> userReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    private static  int count=0;
    //

    @RequestMapping("/shangchuan")
    public String shangchuan() {
        //判断登录，如果未登录则转到登录页
        return "/update";

        //如果已经登录
        //进入动检通首页 /djt/dashboard
    }

  @RequestMapping("/")
   public String index() {
    //判断登录，如果未登录则转到登录页
    return "forward:/login";

   //如果已经登录
     //进入动检通首页 /djt/dashboard
   }

    //登录页
    @GetMapping("/login")
    private String Login() {
        return "login";
    }


    //退出
    @GetMapping("/logout")
    private String logout(HttpServletRequest request,HttpServletResponse response) {
        //注销登录的sid

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies) {
            if("nwtid".equals(cookie.getName())){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);

            }
        }


        //跳转
        return "forward:/login";
    }


    //处理登录方法
    @RequestMapping("/doLogin")
    @ResponseBody
    private int doLogin(@RequestParam(value = "username", required = true) String username,
                        @RequestParam(value = "password", required = true) String password,
                        Model model, HttpServletResponse response) {
        count++;
        int sum=0;
        sum=count+sum;
        LoginType type;
        if (CharMatcher.DIGIT.matchesAllOf(username)) {
            type = LoginType.MOBILE;
        } else if (CharMatcher.is('@').matchesAnyOf(username)) {
            type = LoginType.EMAIL;
        } else {
            type = LoginType.NAME;
        }

        Response<User> userResp = userReadService.login(username, password, type);
        User user = userResp.getResult();
        if (user == null) {
            return -1;
        } else {

            OrganizationUser organizationUser = organizationUserReadService.findOrganizationUserByUserId(user.getId()).getResult();


            if (organizationUser.getOrganizationType() == 1) {
                return 0;
            }


        }
        String id = "" + user.getId();
        Cookie cookie = new Cookie("djtid", id);
        response.addCookie(cookie);


        return 1;


    }


    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("town");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6=new HashMap();
                        map6.put("Province",Province);
                        List<BreedFactory> breedFactoryList= (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3",Province);
                        List<String> citys = breedFactoryReadService.serachAllCity1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList=new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList",cityAreaDtoList);
                        map.put("breedFactorys",breedFactoryList);
                        //switch break;
                      break;
                }


                break;
            }

        }

        return map;
    }


}